package multi_data.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.Map;

/**
 * 多数据源
 *
 * @author 延晓磊
 * @since 2021年07月28日
 */
@Configuration
public class DataSourceConfig {

    @Autowired
    private JpaProperties jpaProperties;
    @Autowired
    private HibernateProperties hibernateProperties;

    /**
     * A 数据源(主)
     *
     * @author 延晓磊
     * @since 2021年07月28日
     */
    @Primary
    @Bean(name = "aDataSource")
    @ConfigurationProperties(prefix = "a.datasource")
    public DataSource aDataSource(){
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    /**
     * B 数据源
     *
     * @author 延晓磊
     * @since 2021年07月28日
     */
    @Bean(name = "bDataSource")
    @ConfigurationProperties(prefix = "b.datasource")
    public DataSource bDataSource(){
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    /**
     * 配置
     */
    @Bean(name = "vendorProperties")
    public Map<String, Object> vendorProperties() {
        return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());
    }
}
